package com.beiding.jsonanalyzer.analyze.select;

import com.beiding.jsonanalyzer.Key;
import com.beiding.jsonanalyzer.analyze.Fetcher;
import com.beiding.jsonanalyzer.analyze.KeyMode;
import com.beiding.jsonanalyzer.analyze.KeyUtils;
import com.beiding.jsonanalyzer.analyze.Segment;
import com.beiding.jsonanalyzer.analyze.func.FuncBase;
import com.beiding.jsonanalyzer.analyze.func.FuncFactory;
import com.beiding.jsonanalyzer.analyze.func.openfunc.FuncUtils;
import com.beiding.jsonanalyzer.analyze.func.base.LastGet;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;


/**
 * 选择构造器
 */
public class SelectorBuilder {

    private List<ForSelector> forSelectors = new ArrayList<>();

    public SelectorBuilder fetch(Object exp,Key alias) {

        FuncFactory fa = FuncUtils.ensureFuncFactory(exp);

        forSelectors.add(selector -> {
            FuncBase funcBase = fa.createInstance();

            selector.getFetchers().add(new Fetcher(funcBase) {
                @Override
                public Map<Object, Object> forOne(Object value) {

                    return Collections.singletonMap(alias, value);
                }
            });

        });

        return this;
    }


    public SelectorBuilder fetch(Object exp) {

        exp = KeyUtils.handleKey(exp, KeyMode.TEXT_TO_KEY);

        if (exp instanceof Key) {

            Key keyW = (Key) exp;

            if (keyW.segmentLength() == 0) {
                return this;
            }

            //截取最后一段
            Segment segment = keyW.segmentAt(keyW.segmentLength() - 1);

            //最后一段如果是任意的
            if (segment.isAny()) {

                Key parent = keyW.subKey(0, keyW.segmentLength() - 1);
                LastGet lastGet = LastGet.of(parent);
                forSelectors.add(selector -> {
                    selector.getFetchers().add(new Fetcher(lastGet.createInstance()) {
                        @Override
                        public Map<Object, Object> forOne(Object value) {
                            if (value instanceof Map) {
                                return (Map<Object, Object>) value;
                            }
                            return Collections.emptyMap();
                        }

                    });
                });


                return this;

            } else if (!segment.isName()) {
                throw new IllegalArgumentException("需要给该抓取结果指定别称:" + exp);
            }
            return fetch(keyW, new Key(Collections.singleton(segment)));
        } else {
            throw new IllegalArgumentException("需要给该抓取结果指定别称:" + exp);
        }

    }


    public Selector build() {
        Selector selector = new Selector();
        for (ForSelector forSelector : forSelectors) {
            forSelector.handle(selector);
        }
        return selector;
    }


    private interface ForSelector {
        void handle(Selector selector);
    }

}
